package com.briup.appointment;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import java.nio.charset.StandardCharsets;
import java.util.Map;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class Support {
    public static String toJson(ObjectMapper om, Object obj) throws Exception {
        return om.writeValueAsString(obj);
    }

    @SuppressWarnings("unchecked")
    public static String loginAndGetToken(MockMvc mockMvc, ObjectMapper om, String username, String password) throws Exception {
        MvcResult result = mockMvc.perform(post("/auth/login")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsString(Map.of("username", username, "password", password))))
                .andExpect(status().isOk())
                .andReturn();
        String body = result.getResponse().getContentAsString(StandardCharsets.UTF_8);
        Map<String, Object> resp = om.readValue(body, Map.class);
        Map<String, Object> data = (Map<String, Object>) resp.get("data");
        return data == null ? null : (String) data.get("token");
    }
}


